<template>
    <view class="container">
        <Loading :show="isLoading" />

        <!-- 订单状态切换 -->
        <view class="order-tabs">
            <view
                v-for="(tab, index) in tabs"
                :key="index"
                class="tab-item"
                :class="{ active: currentTab === index }"
                @click="switchTab(index)"
            >
                {{ tab }}
            </view>
        </view>

        <!-- 订单列表 -->
        <view class="order-list">
            <view v-if="orders.length === 0 && !isLoading" class="empty-state">
                <image
                    src="/static/empty-order.png"
                    mode="aspectFit"
                    class="empty-image"
                ></image>
                <text class="empty-text">暂无订单</text>
            </view>

            <view v-else v-for="order in orders" :key="order.id" class="order-item" @click="goToOrderDetail(order)">
                <view class="order-header">
                    <text class="order-number">订单号：{{ order.orderNo }}</text>
                    <text class="order-status" :class="`status-${order.status}`">
                        {{ getStatusText(order.status) }}
                    </text>
                </view>

                <view class="order-content">
                    <view v-for="detail in order.orderDetail" :key="detail.id" class="product-item">
                        <image
                            :src="detail.productImage"
                            mode="aspectFill"
                            class="product-image"
                        ></image>
                        <view class="product-info">
                            <text class="product-name">{{ detail.productName }}</text>
                            <text class="product-price">¥{{ detail.price }}</text>
                            <text class="product-quantity">x{{ detail.quantity }}</text>
                        </view>
                    </view>
                </view>

                <!-- 优惠券信息 -->
                <view v-if="order.orderCoupon && order.orderCoupon.discountAmount > 0" class="coupon-info">
                    <text class="coupon-text">优惠券：{{ order.orderCoupon.couponName || '优惠券' }} -¥{{ order.orderCoupon.discountAmount }}</text>
                </view>

                <view class="order-footer">
                    <view class="price-info">
                        <text class="total-price">总计：¥{{ order.actualAmount }}</text>
                        <text v-if="order.discountAmount > 0" class="discount-info">优惠：-¥{{ order.discountAmount }}</text>
                    </view>
                    <view class="order-actions">
                        <button
                            v-if="order.status === 0"
                            class="action-btn pay-btn"
                            @click.stop="handlePay(order)"
                        >
                            立即支付
                        </button>
                        <button
                            v-if="order.status === 2"
                            class="action-btn comment-btn"
                            @click.stop="goToReview(order)"
                        >
                            <span v-if="order.status === 2">评论</span>
                            <span v-if="order.status === 5">查看评论</span>
                        </button>
                        <button
                            v-if="order.status === 0 || order.status === 3"
                            class="action-btn delete-btn"
                            @click.stop="handleCancel(order)"
                        >
                            取消订单
                        </button>
                        <button
                            class="action-btn delete-btn"
                            @click.stop="handleDelete(order)"
                        >
                            删除订单
                        </button>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import Loading from "@/components/Loading.vue";
import { getOrderList, deleteOrder, orderCancel } from "@/api/order/index";

// 订单状态标签
const tabs = ["全部", "待支付", "支付中", "支付成功", "已完成", "已取消"];
const currentTab = ref(0);
const isLoading = ref(false);

// 订单数据
const orders = ref<any[]>([]);

// 获取订单状态文本
const getStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '待支付',
        1: '支付中',
        2: '支付成功',
        3: '支付失败',
        4: '已取消',
        5: '已完成'
    };
    return statusMap[status] || '未知状态';
};

// 获取订单状态颜色
const getStatusColor = (status: number) => {
    const colorMap: { [key: number]: string } = {
        0: '#ff6b00',
        1: '#ff6b00',
        2: '#07c160',
        3: '#ff4d4f',
        4: '#999999',
        5: '#07c160'
    };
    return colorMap[status] || '#999999';
};

// 切换订单状态标签
const switchTab = (index: number) => {
    currentTab.value = index;
    getOrders();
};

// 获取订单列表
const getOrders = async () => {
    try {
        isLoading.value = true;
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
            uni.showToast({ title: '请先登录', icon: 'none' });
            return;
        }

        const params: any = {
            userId: userInfo.id,
            pageNum: 1,
            pageSize: 20
        };

        // 根据当前标签筛选状态
        if (currentTab.value > 0) {
            const statusMap = [0, 1, 2, 5, 4]; // 对应标签的状态值
            params.status = statusMap[currentTab.value - 1];
        }

        const res = await getOrderList(params);
        // console.log('getOrders res:', res);
        if (res.code === 200) {
            orders.value = res.rows || [];
            // console.log(orders.value)
        } else {
            uni.showToast({ title: res.msg || '获取订单失败', icon: 'none' });
        }
    } catch (error) {
        console.error('获取订单列表失败:', error);
        uni.showToast({ title: '获取订单失败', icon: 'none' });
    } finally {
        isLoading.value = false;
    }
};

// 跳转到订单详情
const goToOrderDetail = (order: any) => {
    uni.navigateTo({
        url: `/pages/orders/detail?id=${order.id}&orderNo=${order.orderNo}`
    });
};

// 跳转到评论页面
const goToReview = (order: any) => {
    uni.navigateTo({
        url: `/pages/orders/review?orderNo=${order.orderNo}`
    });
};

// 处理支付
const handlePay = (order: any) => {
    uni.navigateTo({
        url: `/pages/orders/create?orderNo=${order.orderNo}`
    });
};

// 删除订单
const handleDelete = (order: any) => {
    uni.showModal({
        title: "提示",
        content: "确认删除该订单？",
        success: async (res) => {
            if (res.confirm) {
                try {
                    isLoading.value = true;
                    const response = await deleteOrder([order.id]);
                    if (response.code === 200) {
                        uni.showToast({
                            title: "删除成功",
                            icon: "success",
                        });
                        getOrders(); // 刷新订单列表
                    } else {
                        uni.showToast({
                            title: response.msg || "删除失败",
                            icon: "none",
                        });
                    }
                } catch (error) {
                    console.error('删除订单失败:', error);
                    uni.showToast({
                        title: "删除失败",
                        icon: "none",
                    });
                }
            }
        },
    });
};

// 取消订单
const handleCancel = (order: any) => {
    uni.showModal({
        title: "提示",
        content: "确认取消该订单？",
        success: async (res) => {
            if (res.confirm) {
                try {
                    isLoading.value = true;
                    const response = await orderCancel(order.orderNo);
                    if (response.code === 200) {
                        uni.showToast({
                            title: "取消成功",
                            icon: "success",
                        });
                        getOrders(); // 刷新订单列表
                    } else {
                        uni.showToast({
                            title: response.msg || "取消失败",
                            icon: "none",
                        });
                    }
                } catch (error) {
                    console.error('取消订单失败:', error);
                    uni.showToast({
                        title: "取消失败",
                        icon: "none",
                    });
                } finally {
                    isLoading.value = false;
                }
            }
        },
    });
};

// 页面加载
onLoad(() => {
    getOrders();
});

// 页面显示时刷新数据
onMounted(() => {
    getOrders();
});
</script>

<style>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
}

.order-tabs {
    display: flex;
    background-color: #ffffff;
    padding: 10px 0;
    position: sticky;
    top: 0;
    z-index: 100;
}

.tab-item {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #666;
    padding: 8px 0;
    position: relative;
}

.tab-item.active {
    color: #007aff;
    font-weight: bold;
}

.tab-item.active::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 2px;
    background-color: #007aff;
}

.order-list {
    padding: 10px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 0;
}

.empty-image {
    width: 120px;
    height: 120px;
    margin-bottom: 10px;
}

.empty-text {
    color: #999;
    font-size: 14px;
}

.order-item {
    background-color: #ffffff;
    border-radius: 8px;
    margin-bottom: 10px;
    padding: 15px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.order-number {
    font-size: 14px;
    color: #666;
}

.order-status {
    font-size: 14px;
}

.status-0 {
    color: #ff6b00;
}

.status-1 {
    color: #ff6b00;
}

.status-2 {
    color: #07c160;
}

.status-3 {
    color: #ff4d4f;
}

.status-4 {
    color: #999999;
}

.status-5 {
    color: #07c160;
}

.order-content {
    margin-bottom: 10px;
}

.product-item {
    display: flex;
    margin-bottom: 8px;
}

.product-item:last-child {
    margin-bottom: 0;
}

.product-image {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    margin-right: 10px;
}

.product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.product-name {
    font-size: 14px;
    color: #333;
}

.product-price {
    font-size: 14px;
    color: #ff6b6b;
}

.product-quantity {
    font-size: 12px;
    color: #999;
}

.coupon-info {
    margin: 10px 0;
    padding: 8px 12px;
    background-color: #fff5f5;
    border: 1px solid #ffd6e7;
    border-radius: 6px;
}

.coupon-text {
    font-size: 12px;
    color: #ff4d4f;
    font-weight: 500;
}

.order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
}

.price-info {
    display: flex;
    flex-direction: column;
}

.total-price {
    font-size: 14px;
    color: #333;
    font-weight: bold;
}

.discount-info {
    font-size: 12px;
    color: #ff6b6b;
    margin-top: 2px;
}

.order-actions {
    display: flex;
    gap: 10px;
}

.action-btn {
    font-size: 12px;
    padding: 4px 12px;
    border-radius: 10px;
    border: none;
}

.pay-btn {
    background-color: #007aff;
    color: #ffffff;
}

.confirm-btn {
    background-color: #007aff;
    color: #ffffff;
}

.delete-btn {
    background-color: #f0f0f0;
    color: #666;
}

.comment-btn {
    background-color: #ffb300;
    color: #fff;
}
</style>
